import fs from 'fs-extra'
import path from 'path'
import readline from 'readline'

const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout
})

function question(prompt) {
  return new Promise((resolve) => {
    rl.question(prompt, resolve)
  })
}

function isValidNumber(str) {
  return /^\d+$/.test(str) && !isNaN(parseInt(str))
}

async function main() {
  try {
    const countInput = await question('Enter number of files to create: ')

    if (!isValidNumber(countInput)) {
      console.log('Error: Number of files must be an integer')
      rl.close()
      return
    }

    const count = parseInt(countInput)

    if (count <= 0) {
      console.log('Error: Number of files must be greater than 0')
      rl.close()
      return
    }

    // 获取起始编号（如果从 index.js 调用会提供，否则默认为 0）
    let startNumber = 0
    try {
      const startInput = await question('Enter start number (or press Enter for auto-detect): ')
      if (startInput.trim() !== '' && isValidNumber(startInput)) {
        startNumber = parseInt(startInput)
      }
    } catch (error) {
      // 如果是从 index.js 调用，可能会直接提供起始编号
      startNumber = 0
    }

    // 确保 product 文件夹存在
    const productPath = path.join(process.cwd(), 'product')
    await fs.ensureDir(productPath)
    console.log('Ensured product folder exists')

    const utilsPath = path.join(process.cwd(), 'utils')
    const utilsExists = await fs.pathExists(utilsPath)

    for (let i = 1; i <= count; i++) {
      const folderNumber = startNumber + i
      const folderName = `product_${folderNumber}`
      const folderPath = path.join(productPath, folderName)

      try {
        await fs.ensureDir(folderPath)
        console.log(`Created folder: product/${folderName}`)

        if (utilsExists) {
          const targetUtilsPath = path.join(folderPath, 'utils')
          await fs.copy(utilsPath, targetUtilsPath)
          console.log(`Copied utils to product/${folderName}`)
        } else {
          console.log('Warning: utils folder not found in current directory')
        }
      } catch (error) {
        console.log(`Failed to create or copy to product/${folderName}: ${error.message}`)
      }
    }

    console.log(`All ${count} folders created in product directory starting from product_${startNumber + 1}!`)
    rl.close()
  } catch (error) {
    console.error('Error:', error.message)
    rl.close()
  }
}

main()